package com.kgc.mall.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//MyBatis工具类
public class MyBatisUtil {
    private final static  String RESOURCE = "MyBatis-Config.xml";

    private static ThreadLocal<SqlSession> sessionTL = new ThreadLocal<SqlSession>();

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        InputStream inputStream = null;
        try{
            inputStream = Resources.getResourceAsStream(RESOURCE);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            {
                if (null != inputStream){
                    try {
                        inputStream.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 获取数据库会话
     */
    public static SqlSession newSession(){
        if(sessionTL.get() == null){
            SqlSession session = sqlSessionFactory.openSession();
            sessionTL.set(session);
        }
        return sessionTL.get();
    }

    /**
     *关闭数据库会话
     */
    public static void closeSession(){
        SqlSession session = sessionTL.get();
        if(null != session){
            session.close(); //关闭session
            sessionTL.set(null); //清空本地线程变量里面session
            sessionTL.remove(); //防止内存泄露
        }
    }

    /**
     * 获取Mapper接口代理对象
     */
    public static <T> T getMapper(Class<T> clazz) {
        SqlSession session = newSession();
        T t = session.getMapper(clazz);
        return t;
    }

    /**
     * 提交事务+释放资源
     */
    public static void commit() {
        try {
            SqlSession session = newSession();
            session.commit();
        } catch (RuntimeException e) {
            throw e;
        }finally {
            closeSession();
        }
    }

    /**
     * 回滚事务+释放资源
     */
    public static void rollback() {
        try {
            SqlSession session = newSession();
            session.rollback();
        } catch (RuntimeException e) {
            throw e;
        }finally {
            //释放资源
            closeSession();
        }
    }
}
